package com.sk.weichat.ui.groupchat;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.bean.ApplyInfoBean;
import com.sk.weichat.bean.message.GroupMessage;
import com.sk.weichat.db.dao.GroupMessageDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.contacts.GroupManagerSetActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.message.MucChatActivity;
import com.sk.weichat.ui.message.multi.EventGroupStatus;
import com.sk.weichat.ui.message.multi.RoomInfoActivity;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.PreferenceUtils;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.CustomPopupWindow;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.xuan.xuanhttplibrary.okhttp.result.Result;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

/**
 * @Author: swy
 * @ClassName: RefuseGroupApplyActivity
 * @Description: 拒绝申请、邀请详情页
 * @CreateDate: 2019/9/23 10:00
 */
public class RefuseGroupApplyActivity extends BaseActivity implements View.OnClickListener {

    private ImageView imgUserHead;
    private TextView tvUserName;
    private TextView tvApplyTime;
    private TextView tvApplyContent;
    private LinearLayout ll_dispose;
    private TextView tv_dispose_name;
    private TextView tvState;

    private String msgId;//进群申请的消息id
    private GroupMessage mGroupMessage;
    private TextView mTvTitle;
    private TextView tvApplyOpinion;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_refuse_group_apply);
        msgId = getIntent().getStringExtra("msgId");
        mGroupMessage = GroupMessageDao.getInstance().getGroupMessage(coreManager.getSelf().getUserId(), msgId);
        initAction();
        initView();
    }

    private void initAction() {
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTvTitle = findViewById(R.id.tv_title_center);
        mTvTitle.setText("拒绝申请");
    }

    private void initView() {
        imgUserHead = findViewById(R.id.img_user_head);
        tvUserName = findViewById(R.id.tv_user_name);
        tvApplyTime = findViewById(R.id.tv_apply_time);
        tvApplyContent = findViewById(R.id.tv_apply_content);
        tvApplyOpinion = findViewById(R.id.tv_apply_opinion);
        ll_dispose = findViewById(R.id.ll_apply);
        tv_dispose_name = findViewById(R.id.tv_dispose_name);
        tvState = findViewById(R.id.tv_state);
        tvApplyTime.setText(TimeUtils.getFriendlyTimeDesc(this, mGroupMessage.getTimeSend()));
        tvState.setOnClickListener(this);
        ll_dispose.setOnClickListener(this);
        imgUserHead.setOnClickListener(this);

        String content;
        switch (mGroupMessage.getState()) {
            case GroupMessage.STATUS_GM_20:
                //拒绝邀请
                mTvTitle.setText("拒绝邀请");
                if (mGroupMessage.getIsGroup() == 1) {
                    tvState.setText("该邀请已失效");
                    tvState.setBackgroundResource(R.drawable.bg_border_btn_gray);
                    tvState.setEnabled(false);
                } else {
                    tvState.setText("再次邀请");
                }
                tvUserName.setText(mGroupMessage.getRoomName());
                content = "拒绝你的邀请";
                tvApplyContent.setText(content);
                tvApplyOpinion.setText(TextUtils.isEmpty(mGroupMessage.getOpinion()) ? "" : mGroupMessage.getOpinion());
                AvatarHelper.getInstance().displayAvatar(mGroupMessage.getOwnerId(), mGroupMessage, imgUserHead);
                tv_dispose_name.setText(mGroupMessage.getHandler());
                break;

            case GroupMessage.STATUS_GM_21:
                //拒绝申请
                mTvTitle.setText("拒绝申请");
                tvState.setText("申请加群");
                tvUserName.setText(mGroupMessage.getRoomName());
                content = "已拒绝让你加入群";
                tvApplyContent.setText(content);
                tvApplyOpinion.setText(TextUtils.isEmpty(mGroupMessage.getOpinion()) ? "" : mGroupMessage.getOpinion());
                AvatarHelper.getInstance().displayAvatar(mGroupMessage.getOwnerId(), mGroupMessage, imgUserHead);
                tv_dispose_name.setText(mGroupMessage.getHandler());
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_state://申请（邀请）进群
                switch (mGroupMessage.getState()) {
                    case GroupMessage.STATUS_GM_20:
                        //拒绝邀请
                        inviteFriend(mGroupMessage.getToUserId());
                        break;
                    case GroupMessage.STATUS_GM_21:
                        //拒绝申请
                        roomAutoJoin();
                        break;
                }
                break;

            case R.id.ll_apply://处理人
                Intent intent = new Intent(mContext, PersonalCenterActivity.class);
                intent.putExtra(AppConstant.EXTRA_USER_ID, mGroupMessage.getHandlerId());
                mContext.startActivity(intent);
                break;

            case R.id.img_user_head://点击头像
                clickAvatar();
                break;
        }

    }

    private void clickAvatar() {
        Intent intent;
        switch (mGroupMessage.getState()) {
            case GroupMessage.STATUS_GM_20:
                mGroupMessage = GroupMessageDao.getInstance().getGroupMessage(coreManager.getSelf().getUserId(), msgId);
                //拒绝邀请
                if (mGroupMessage.getIsGroup() == 1) {//不在群内
                    startActivity(new Intent(mContext, OpenGroupInfoActivity.class)
                            .putExtra("RoomId", mGroupMessage.getRoomId())
                            .putExtra("packetId", msgId));
                } else {
                    intent = new Intent(mContext, RoomInfoActivity.class);
                    intent.putExtra(AppConstant.EXTRA_USER_ID, mGroupMessage.getUserId());
                    intent.putExtra(AppConstant.EXTRA_IS_GROUP_CHAT, true);
                    mContext.startActivity(intent);
                }

                break;

            case GroupMessage.STATUS_GM_21:
                //拒绝申请
                startActivity(new Intent(mContext, OpenGroupInfoActivity.class)
                        .putExtra("RoomId", mGroupMessage.getRoomId())
                        .putExtra("packetId", msgId));
                break;
        }
    }


    /**
     * 邀请好友
     */
    private void inviteFriend(String userIds) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", mGroupMessage.getRoomId());
        params.put("userIds", userIds);
        DialogHelper.showDefaulteMessageProgressDialog(this);

        HttpUtils.get().url(coreManager.getConfig().ROOM_INVITE_AUTO_JINO)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() ==1) {
                            ToastUtil.showToast(mContext, getString(R.string.invite_success));
                            EventBus.getDefault().post(new EventGroupStatus(111111, 0));//通知群列表刷新
                            setResult(RESULT_OK);
                            finish();
                        } else if (result.getResultCode() == 1040320) {//
                            startActivityForResult(new Intent(RefuseGroupApplyActivity.this, InviteJoinRoomActivity.class).putExtra("roomId", mGroupMessage.getRoomId()).putExtra("userIds", mGroupMessage.getToUserId()), 100);
                        } else if (result.getResultCode() == 1040319) {//已加入群 已在群内
                            ToastUtil.showToast(RefuseGroupApplyActivity.this, result.getResultMsg());
                            EventBus.getDefault().post("cancle");//关闭页面
                            //进入群聊页面
                            Intent intent = new Intent(RefuseGroupApplyActivity.this, MucChatActivity.class);
                            intent.putExtra(AppConstant.EXTRA_USER_ID, mGroupMessage.getUserId());
                            intent.putExtra(AppConstant.EXTRA_NICK_NAME, mGroupMessage.getRoomName());
                            intent.putExtra(AppConstant.EXTRA_IS_GROUP_CHAT, true);
                            startActivity(intent);
                            finish();
                        } else if (result.getResultCode()==1040329){//必须是群成员才能邀请

                            tvState.setText("该邀请已失效");
                            tvState.setBackgroundResource(R.drawable.bg_border_btn_gray);
                            tvState.setEnabled(false);
                            //重新获取 该消息
                            mGroupMessage = GroupMessageDao.getInstance().getGroupMessage(coreManager.getSelf().getUserId(), msgId);
                            ToastUtil.showToast(RefuseGroupApplyActivity.this,result.getResultMsg());
                        }else {
                            ToastUtil.showToast(RefuseGroupApplyActivity.this,result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showNetError(mContext);
                    }
                });
    }

    /**
     * @author: czl
     * @description 申请加群
     * @date: 2019/9/18 9:28
     */
    private void roomAutoJoin() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", mGroupMessage.getRoomId());
        DialogHelper.showDefaulteMessageProgressDialog(RefuseGroupApplyActivity.this);

        HttpUtils.post().url(coreManager.getConfig().ROOM_AUTO_JOIN)
                .params(params).build().execute(new BaseCallback<String>(String.class) {
            @Override
            public void onResponse(ObjectResult<String> result) {
                DialogHelper.dismissProgressDialog();
                if (result.getResultCode() == 1) {//加入成功 直接进群
                    EventBus.getDefault().post("cancle");//关闭页面
                    //进入群聊页面
                    Intent intent = new Intent(RefuseGroupApplyActivity.this, MucChatActivity.class);
                    intent.putExtra(AppConstant.EXTRA_USER_ID, mGroupMessage.getUserId());
                    intent.putExtra(AppConstant.EXTRA_NICK_NAME, mGroupMessage.getRoomName());
                    intent.putExtra(AppConstant.EXTRA_IS_GROUP_CHAT, true);
                    startActivity(intent);
                    finish();
                } else if (result.getResultCode() == 1040320) {//群主开启了加群验证  跳转到发送加群申请页面
                    startActivity(new Intent(RefuseGroupApplyActivity.this, ApplyForAddGroupActivity.class)
                            .putExtra("RoomId", mGroupMessage.getRoomId()));

                } else if (result.getResultCode() == 1040319) {//已加入群 已在群内
                    ToastUtil.showToast(RefuseGroupApplyActivity.this, result.getResultMsg());
                    EventBus.getDefault().post("cancle");//关闭页面
                    //进入群聊页面
                    Intent intent = new Intent(RefuseGroupApplyActivity.this, MucChatActivity.class);
                    intent.putExtra(AppConstant.EXTRA_USER_ID, mGroupMessage.getUserId());
                    intent.putExtra(AppConstant.EXTRA_NICK_NAME, mGroupMessage.getRoomName());
                    intent.putExtra(AppConstant.EXTRA_IS_GROUP_CHAT, true);
                    startActivity(intent);
                    finish();
                } else {
                    ToastUtil.showToast(RefuseGroupApplyActivity.this, result.getResultMsg());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showErrorNet(RefuseGroupApplyActivity.this);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

        }
    }
}
